package com.emm.yixun.website.controller.hotfix;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.emm.yixun.common.model.*;
import com.emm.yixun.common.model.dto.*;
import com.emm.yixun.marketing.service.HaveAdvanceRefundServiceFacade;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.emm.yixun.common.excel.FastExcel;
import com.emm.yixun.common.model.enums.BusinessTypeEnum;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.ReceivablesTypeEnum;
import com.emm.yixun.common.model.enums.RoomStatusEnum;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.BeanUtil;
import com.emm.yixun.common.utils.DateUtils;
import com.emm.yixun.customer.service.CustomerServiceFacade;
import com.emm.yixun.customer.service.SignedServiceFacade;
import com.emm.yixun.customer.service.SubscribeServiceFacade;
import com.emm.yixun.estate.service.HotfixServiceFacade;
import com.emm.yixun.estate.service.ProjectBuildingServiceFacade;
import com.emm.yixun.estate.service.ProjectPremisesIndustDataServiceFacade;
import com.emm.yixun.estate.service.ProjectPremisesIndustDataVersionServiceFacade;
import com.emm.yixun.estate.service.ProjectPremisesServiceFacade;
import com.emm.yixun.estate.service.ProjectRoomServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.marketing.service.HaveReceiveRefundServiceFacade;
import com.emm.yixun.marketing.service.NeedReceiveRefundServiceFacade;
import com.emm.yixun.system.service.BaseCodeValueServiceFacade;
import com.emm.yixun.system.service.UserServiceFacade;
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.vo.estate.IndustExcelVo;

/**
 * 修复业态数据
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = "hoxfit")
public class HotfixIndustController extends BaseController<ProjectPremisesIndustData> {

	@Autowired
	private ProjectServiceFacade projectservice;

	@Autowired
	private ProjectPremisesServiceFacade projectPremisesService;

	@Autowired
	private ProjectBuildingServiceFacade projectbuildingService;

	@Autowired
	private ProjectPremisesIndustDataServiceFacade industDataService;

	@Autowired
	private ProjectPremisesIndustDataVersionServiceFacade versionService;

	@Autowired
	private BaseCodeValueServiceFacade baseCodeValueService;

	@Autowired
	private ProjectRoomServiceFacade projectRoomservice;

	@Autowired
	private SubscribeServiceFacade subscribeServiceFacade;

	@Autowired
	private SignedServiceFacade signedServiceFacade;

	@Autowired
	private HaveReceiveRefundServiceFacade haveReceiveRefundServiceFacade;

	@Autowired
	private HaveAdvanceRefundServiceFacade haveAdvanceRefundServiceFacade;

	@Autowired
	private NeedReceiveRefundServiceFacade needReceiveRefundServiceFacade;

	@Autowired
	private HotfixServiceFacade hotfixServiceFacade;
	
	@Autowired
	private CustomerServiceFacade customerServiceFacade;

	@Autowired
	private UserServiceFacade userServiceFacade;

	/**
	 * 修复程序
	 * 
	 * @return
	 */
	@RequestMapping(value = "hoxfitExcel")
	public @ResponseBody AjaxRes hoxfitExcel() {
		// 得到數據
		List<IndustExcelVo> list = getExcelValue();
		readSource(list);
		return getAjaxRes();
	}

	public List<IndustExcelVo> getExcelValue() {
		List<IndustExcelVo> array = new ArrayList<IndustExcelVo>();
		try {
			File file = new File("C:\\Users\\Administrator\\Desktop\\test.xlsx");
			InputStream inputStream = new FileInputStream(file);
			FastExcel fastExcel = new FastExcel(inputStream);
			fastExcel.setStartRow(1);
			array = fastExcel.parse(IndustExcelVo.class);
			fastExcel.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return array;
	}

	/**
	 * 處理數據
	 * 
	 * @param list
	 */
	public void readSource(List<IndustExcelVo> list) {
		try {
			for (IndustExcelVo vo : list) {
				ProjectDto project = new ProjectDto();
				project.setDelFlag(DelFlagEnum.UNDEL.getNo());
				project.setProjectName(vo.getProjectName());
				ResponseList<Project> responseProList = projectservice.findByDto(project);
				Long projectId = responseProList.getEntity().get(0).getId();
				// 組團
				ProjectPremisesDto premisesDto = new ProjectPremisesDto();
				premisesDto.setProjectId(projectId);
				premisesDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				premisesDto.setGroupName(vo.getGroupName());
				ResponseList<ProjectPremises> responsePreList = projectPremisesService.findByDto(premisesDto);
				Long premisesId = responsePreList.getEntity().get(0).getId();

				// 新增業態
				ProjectPremisesIndustDataDto createIndust = new ProjectPremisesIndustDataDto();
				BeanUtil.convert2T(createIndust, vo);
				createIndust.setUpdateTime(new Date());
				createIndust.setTargetAveragPrice(new BigDecimal("0"));
				BaseCodeValueDto value = new BaseCodeValueDto();
				value.setCodeValue(vo.getIndustMark());
				ResponseList<BaseCodeValue> baseValueList = baseCodeValueService.findByDto(value);
				if (baseValueList.isSuccess() && baseValueList.getEntity() != null
						&& baseValueList.getEntity().size() > 0) {
					createIndust.setIndustMark(baseValueList.getEntity().get(0).getId() + "");
				} else {
					createIndust.setIndustMark("90");
				}
				createIndust.setProjectId(projectId);
				createIndust.setPremisesId(premisesId);
				if (!StringUtils.isEmpty(vo.getSalableAcreag())) // 自持面積
					createIndust.setSelfSustaiAcreag(new BigDecimal(vo.getSalableAcreag()));
				if (!StringUtils.isEmpty(vo.getNumberOfBuildi()))
					createIndust.setNumberOfBuildi(new Integer(vo.getNumberOfBuildi()));// 棟數
				if (!StringUtils.isEmpty(vo.getNumberLayers())) // 層數
					createIndust.setNumberLayers(new Integer(vo.getNumberLayers()));
				if (!StringUtils.isEmpty(vo.getTotalHouse()))
					createIndust.setTotalHouse(new Integer(vo.getTotalHouse()));// 總戶數
				if (!StringUtils.isEmpty(vo.getSalableAcreag())) // 可售面積
					createIndust.setSalableAcreag(new BigDecimal(vo.getSalableAcreag()));
				if (!StringUtils.isEmpty(vo.getGroundSalesAcreag())) // 地上可售面積
					createIndust.setGroundSalesAcreag(new BigDecimal(vo.getGroundSalesAcreag()));
				if (!StringUtils.isEmpty(vo.getUndergSalesAcreag())) // 地下
					createIndust.setUndergSalesAcreag(new BigDecimal(vo.getUndergSalesAcreag()));
				if (!StringUtils.isEmpty(vo.getTargetValue())) // 自持貨值
					createIndust.setTargetValue(new BigDecimal(vo.getTargetValue()));

				Response<ProjectPremisesIndustDataDto> industVo = industDataService.save(createIndust);

				// 新增版本信息
				String[] version = vo.getVersionName().split(",");
				String[] effect = vo.getEffectStartTime().split(",");
				String[] versionValue = vo.getVersionValue().split(",");
				for (int j = 0; j < version.length; j++) {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
					ProjectPremisesIndustDataVersionDto versionCreate = new ProjectPremisesIndustDataVersionDto();
					versionCreate.setIndustId(industVo.getEntity().getId());
					versionCreate.setVersionName(version[j]);
					versionCreate.setEffectStartTime(df.parse(effect[j]));
					versionCreate.setVersionValue(new BigDecimal(versionValue[j]));
					versionCreate.setTargetType("1");
					versionCreate.setUpdateTime(new Date());
					versionCreate.setDelFlag(DelFlagEnum.UNDEL.getNo());
					versionCreate.setCreateTime(new Date());
					versionCreate.setPremisesId(premisesId);
					versionService.save(versionCreate);

				}
				// 樓棟
				if (!StringUtils.isEmpty(vo.getBuildingName())) {
					String[] buildList = vo.getBuildingName().split(",");
					if (buildList != null && buildList.length > 0) {

						for (int i = 0; i < buildList.length; i++) {
							ProjectBuildingDto build = new ProjectBuildingDto();
							build.setProjectId(projectId);
							build.setPremisesId(premisesId);
							build.setBuildingName(buildList[i]);
							build.setDelFlag(DelFlagEnum.UNDEL.getNo());
							ResponseList<ProjectBuilding> buildingList = projectbuildingService.findByDto(build);
							if (buildingList.isSuccess() && buildingList.getEntity() != null
									&& buildingList.getEntity().size() > 0) {
								ProjectBuilding budild = buildingList.getEntity().get(0);
								// 樓棟下面所有房間的液態
								ProjectRoomDto room = new ProjectRoomDto();
								room.setDelFlag(DelFlagEnum.UNDEL.getNo());
								room.setProjectId(projectId);
								room.setPremisesId(premisesId);
								room.setBuildingId(budild.getId());
								ResponseList<ProjectRoom> roomList = projectRoomservice.findByDto(room);
								if (roomList.isSuccess() && roomList.getEntity() != null
										&& roomList.getEntity().size() > 0) {
									for (ProjectRoom updateObj : roomList.getEntity()) {
										ProjectRoomDto roomDto = new ProjectRoomDto();
										roomDto.setId(updateObj.getId());
										if (baseValueList.isSuccess() && baseValueList.getEntity() != null
												&& baseValueList.getEntity().size() > 0) {
											roomDto.setIndustMark(baseValueList.getEntity().get(0).getId() + "");
										} else {
											roomDto.setIndustMark("90");
										}

										projectRoomservice.updateByPrimaryKey(roomDto, true);
									}
								}
							}

						}

					}
				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 修复认购时间
	 * 
	 * @param subId
	 * @param subDate
	 * @return
	 * @Description:
	 */
	@RequestMapping(value = "updateSubDate")
	public @ResponseBody AjaxRes updateSubDate(Long subId, String subDate) {
		AjaxRes ar = getAjaxRes();
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "data:repair:subscribeDate"))) {
			try {
				SubscribeDto entity = new SubscribeDto();
				entity.setId(subId);
				entity.setSubscribeDate(DateUtils.StringToDate(subDate));
				entity.setCheckDate(DateUtils.StringToDate(subDate));
				subscribeServiceFacade.updateByPrimaryKey(entity, true);
				ar.setRes(Const.SUCCEED);
			} catch (Exception e) {
				logger.error("updateSubDate error: ", e);
				ar.setRes(Const.FAIL);
			}
		} else {
			ar.setRes(Const.NO_AUTHORIZED);
		}
		return ar;
	}

	@RequestMapping(value = "updateSignedDate")
	public @ResponseBody AjaxRes updateSignedDate(Long sigId, String sigDate) {
		AjaxRes ar = getAjaxRes();
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "data:repair:signeDate"))) {
			try {
				Date date = DateUtils.StringToDate(sigDate);
				SignedDto entity = new SignedDto();
				entity.setId(sigId);
				entity.setDidTime(date);
				entity.setCheckDate(date);
				signedServiceFacade.updateByPrimaryKey(entity, true);
				ar.setRes(Const.SUCCEED);
			} catch (Exception e) {
				logger.error("updateSignedDate error: ", e);
				ar.setRes(Const.FAIL);
			}
		} else {
			ar.setRes(Const.NO_AUTHORIZED);
		}
		return ar;
	}

	@RequestMapping(value = "updateHaveReceiveRefundDate")
	public @ResponseBody AjaxRes updateHaveReceiveRefundDate(Long haveId, String statementDate) {
		AjaxRes ar = getAjaxRes();
		try {
			if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "data:repair:haveReceiveDate"))) {
				HaveReceiveRefundDto entity = new HaveReceiveRefundDto();
				entity.setId(haveId);
				entity.setStatementDate(DateUtils.StringToDate(statementDate));
				haveReceiveRefundServiceFacade.updateByPrimaryKey(entity, true);
				ar.setRes(Const.SUCCEED);
			} else {
				ar.setRes(Const.NO_AUTHORIZED);
			}
		} catch (Exception e) {
			logger.error("updateHaveReceiveRefundDate error: ", e);
			ar.setRes(Const.FAIL);
		}
		return ar;
	}

	@RequestMapping(value = "updateHaveAdvanceRefundDate")
	public @ResponseBody AjaxRes updateHaveAdvanceRefundDate(Long haveId, String statementDate) {
		AjaxRes ar = getAjaxRes();
		try {
			if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "data:repair:haveReceiveDate"))) {
				HaveAdvanceRefundDto entity = new HaveAdvanceRefundDto();
				entity.setId(haveId);
				entity.setStatementDate(DateUtils.StringToDate(statementDate));
				haveAdvanceRefundServiceFacade.updateByPrimaryKey(entity, true);
				ar.setRes(Const.SUCCEED);
			} else {
				ar.setRes(Const.NO_AUTHORIZED);
			}
		} catch (Exception e) {
			logger.error("updateHaveAdvanceRefundDate error: ", e);
			ar.setRes(Const.FAIL);
		}
		return ar;
	}

	@RequestMapping(value = "findHaveReceiveRefundById")
	public @ResponseBody HaveReceiveRefund findById(Long id) {
		return haveReceiveRefundServiceFacade.findById(id).getEntity();
	}

	@RequestMapping(value = "findHaveAdvanceRefundById")
	public @ResponseBody HaveAdvanceRefund findHaveAdvanceRefundById(Long id) {
		return haveAdvanceRefundServiceFacade.findById(id).getEntity();
	}

	/**
	 * 认购修复删除
	 * 
	 * @param subId
	 * @return
	 * @Description:
	 */
	@RequestMapping(value = "subscribeDeleteHotfix")
	public @ResponseBody AjaxRes subscribeDeleteHotfix(Long subId) {
		AjaxRes ar = getAjaxRes();
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "data:repair:subscribeDelete"))) {
			try {
				Response<Subscribe> resSub = subscribeServiceFacade.findById(subId);
				if(!resSub.isSuccess() || resSub.getEntity() == null) {
					ar.setRes(Const.FAIL);
					return ar;
				}
				Subscribe sub = resSub.getEntity();
				// 删除待收款记录
				NeedReceiveRefundDto needEntity = new NeedReceiveRefundDto();
				needEntity.setRelationId(subId);
				needEntity.setBusinessType(BusinessTypeEnum.SUBSCRIBE.getNo());
				needReceiveRefundServiceFacade.deleteByDto(needEntity);
				// 删除已收款记录
				HaveReceiveRefundDto haveEntity = new HaveReceiveRefundDto();
				haveEntity.setRelationId(subId);
				haveEntity.setStatementType(new Long(ReceivablesTypeEnum.SUBSCRIBE.getNo()));
				haveReceiveRefundServiceFacade.deleteByDto(haveEntity);
				// 删除认购记录
				subscribeServiceFacade.deleteByPrimaryKey(subId);
				// 修改房间状态为可售
				ProjectRoomDto dto = new ProjectRoomDto();
				dto.setId(sub.getRoomId());
				dto.setRoomStatus(RoomStatusEnum.VENDIBILITY.getNo());
				projectRoomservice.updateByDto(dto);
				
				ar.setRes(Const.SUCCEED);
			} catch (Exception e) {
				logger.error("subscribeDeleteHotfix error: ", e);
				ar.setRes(Const.FAIL);
			}
		} else {
			ar.setRes(Const.NO_AUTHORIZED);
		}
		return ar;
	}

	/**
	 * 签约删除
	 * 
	 * @param subId
	 * @return
	 * @Description:
	 */
	@RequestMapping(value = "signedDeleteHotfix")
	public @ResponseBody AjaxRes signedDeleteHotfix(Long sigId) {
		AjaxRes ar = getAjaxRes();
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "hoxfit:signedDeleteHotfix"))) {
			try {
				// 删除待收款记录，已收款记录，认购记录
				NeedReceiveRefundDto needEntity = new NeedReceiveRefundDto();
				needEntity.setRelationId(sigId);
				needEntity.setBusinessType(BusinessTypeEnum.SIGNED.getNo());
				needReceiveRefundServiceFacade.deleteByDto(needEntity);
				HaveReceiveRefundDto haveEntity = new HaveReceiveRefundDto();
				haveEntity.setRelationId(sigId);
				haveEntity.setStatementType(new Long(ReceivablesTypeEnum.SIGNED.getNo()));
				haveReceiveRefundServiceFacade.deleteByDto(haveEntity);
				signedServiceFacade.deleteByPrimaryKey(sigId);
				ar.setRes(Const.SUCCEED);
			} catch (Exception e) {
				logger.error("signedDeleteHotfix error: ", e);
				ar.setRes(Const.FAIL);
			}
		} else {
			ar.setRes(Const.NO_AUTHORIZED);
		}
		return ar;

	}

	/**
	 * 删除待收款记录
	 * 
	 * @param id
	 * @return
	 * @Description:
	 */
	@RequestMapping(value = "needReceiveDelete")
	public @ResponseBody AjaxRes needReceiveDelete(Long id) {
		AjaxRes ar = getAjaxRes();
		try {
			if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "data:repair:needReceiveDelete"))) {
				Response<NeedReceiveRefund> response = needReceiveRefundServiceFacade.findById(id);
				if (response.isSuccess() && response.getEntity() != null) {
					NeedReceiveRefund needReceiveRefund = response.getEntity();
					HaveReceiveRefundDto haveReceiveRefund = new HaveReceiveRefundDto();
					haveReceiveRefund.setReceivablesId(needReceiveRefund.getId());
					ResponseList<HaveReceiveRefund> haveList = haveReceiveRefundServiceFacade
							.findByDto(haveReceiveRefund);
					if (haveList.isSuccess() && haveList.getEntity() != null && haveList.getEntity().size() > 0) { // 已结清，存在已收款记录，不能删除
						ar.setRes(Const.FAIL);
						ar.setResMsg("已存在收款记录,不能删除!");
					} else if (needReceiveRefund.getStatus().equals("1")) {
						User user = ShiroUtil.getCurrentUser();
						NeedReceiveRefundDto dto = new NeedReceiveRefundDto();
						dto.setDelFlag(DelFlagEnum.DEL.getNo());
						dto.setUpdateUserId(user.getId());
						// needReceiveRefundServiceFacade.deleteByPrimaryKey(id);
						dto.setId(id);
						needReceiveRefundServiceFacade.updateByPrimaryKey(dto, true);
						ar.setRes(Const.SUCCEED);
						return ar;
					}

				}
			} else {
				ar.setRes(Const.NO_AUTHORIZED);
			}
		} catch (Exception e) {
			logger.error("needReceiveDelete error: ", e);
			ar.setRes(Const.FAIL);
		}
		return ar;
	}

	/**
	 *
	 * @Title: hotfix @Description: 垃圾的修补程序 @param @param id @param @return
	 *         设定文件 @return AjaxRes 返回类型 @throws
	 */
	@RequestMapping(value = "hotfix_pmo")
	public @ResponseBody AjaxRes hotfix_pmo(Long id) {
		AjaxRes res = getAjaxRes();
		String value = hotfixServiceFacade.hotfixIndust(id);
		if (StringUtils.isEmpty(value)) {
			res.setResMsg("调用成功");
		} else {
			res.setResMsg(value);
		}
		return res;
	}

	@RequestMapping(value = "customerInfoHoxfix")
	public @ResponseBody AjaxRes customerInfoHoxfix(Long projectId) {
		AjaxRes ar = getAjaxRes();
		Response<Boolean> res = customerServiceFacade.hotfixCustomerSignedInfo(getExcelInfo(), projectId);
		ar.setObj(res.getEntity());
		ar.setResMsg(res.getResultMessage());
		return ar;
	}

	public List<SignedCustomerVo> getExcelInfo() {
		List<SignedCustomerVo> array = new ArrayList<SignedCustomerVo>();
		try {
			File file = new File("C:\\Users\\Administrator\\Desktop\\玉园.xlsx");
			InputStream inputStream = new FileInputStream(file);
			FastExcel fastExcel = new FastExcel(inputStream);
			fastExcel.setStartRow(1);
			array = fastExcel.parse(SignedCustomerVo.class);
			fastExcel.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return array;
	}

	public List<OaUserExcelDto> getOaUserCodeList() {
		List<OaUserExcelDto> array = new ArrayList<OaUserExcelDto>();
		try {
			File file = new File("C:\\Users\\Administrator\\Desktop\\excelOa.xls");
			InputStream inputStream = new FileInputStream(file);
			FastExcel fastExcel = new FastExcel(inputStream);
			fastExcel.setStartRow(1);
			array = fastExcel.parse(OaUserExcelDto.class);
			fastExcel.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return array;
	}

	@RequestMapping(value = "hotFixOaUserCode")
	@ResponseBody
	public AjaxRes hotFixOaUserCode() {
		AjaxRes ajax = getAjaxRes();
		List<OaUserExcelDto> oaList = getOaUserCodeList();
		Response<String> result = userServiceFacade.hotFixUserCode(oaList);
		ajax.setResMsg(result.getEntity());
		return ajax;
	}
}
